//
//  WNRefreshiControl.swift
//  XLWeibo
//
//  Created by 风不会停息 on 2017/7/29.
//  Copyright © 2017年 风不会停息. All rights reserved.
//

import UIKit

let WNRefreshContrlH : CGFloat = 50

enum WNRefreshControlType {
    case normal // 正常
    case pulling // 松手就刷新
    case refreshing //刷新中
}


class WNRefreshiControl: UIControl {

    var refreshType : WNRefreshControlType = .normal{
        didSet{
            
            switch refreshType {
            case .normal:
                //显示箭头
                iconImageView.isHidden = false
                
                //停止风火轮
                indicatorView.stopAnimating()
                
                UIView.animate(withDuration: 0.25, animations: {
                    
                    
                }, completion: { (_) in
                    
                    if oldValue == .refreshing {
                        
                        UIView.animate(withDuration: 0.25, animations: {
                            self.currentScrollView?.contentInset.top -= WNRefreshContrlH
                        })
                    }
                })
                
                messageLabel.text = "下拉刷新"
                
            case .pulling:
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.iconImageView.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
                })
                
                messageLabel.text = "松手就刷新"
                
            case .refreshing:
                
                iconImageView.isHidden = true
                
                indicatorView.startAnimating()
                
                messageLabel.text = "正在刷新..."
                
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.currentScrollView?.contentInset.top += WNRefreshContrlH
                    
                }, completion: { (_) in
                    
                    self.sendActions(for: .valueChanged)
                })
         
            }
        }
    }

    //当前控件的父视图
    var currentScrollView : UIScrollView?
    
    // MARK:---- 懒加载控件
    //  箭头
    fileprivate lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //  刷新内容
    fileprivate lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.text = "下拉刷新"
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = UIColor.gray
        return label
    }()
    //  刷新风火轮
    fileprivate lazy var indicatorView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private func setupUI (){
        
        backgroundColor = UIColor.purple
        
        addSubview(iconImageView)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
        //取消控件的自动布局
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        //系统方法添加约束
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerY, relatedBy: .equal , toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerX, relatedBy: .equal , toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal , toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
         addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal , toItem: iconImageView, attribute: .trailing, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal , toItem: iconImageView, attribute: .centerX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal , toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
    }
    
    //将要添加父视图时调用
    override func willMove(toSuperview newSuperview: UIView?) {
        
        guard let scrollView = newSuperview as? UIScrollView else{
            return
        }
        self.frame = CGRect(x: 0, y: 0-WNRefreshContrlH, width: scrollView.frame.size.width, height: WNRefreshContrlH)
        
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        
        currentScrollView = scrollView
    }
    
    //kvo监听方法重写
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let contentOffSetY = currentScrollView!.contentOffset.y
        
        //是否为松手状态
        if currentScrollView!.isDragging {
            
            //判断是进入刷新状态还是临界值
            let limitMaxY = -(currentScrollView!.contentInset.top + WNRefreshContrlH)
            
            if contentOffSetY < limitMaxY && refreshType == .normal {
                
                refreshType = .pulling
            }
            else if refreshType == .pulling && contentOffSetY >= limitMaxY {
                
                refreshType = .normal
            }
        }
        else{
            
            if refreshType == .pulling{
                
                refreshType = .refreshing
            }
        }
    }
    
    func endRefreshing(){
        
        refreshType = .normal
    }
    
    deinit {
        
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
